package com.googlecode.grima.bpm;

import java.util.ArrayList;
import java.util.List;

import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.Group;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

public class ActivitiUserDetailsService implements UserDetailsService {

	@Autowired
	IdentityService identityService;

	@Override
	@Transactional
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		org.activiti.engine.identity.User user = identityService.createUserQuery().userId(username).singleResult();

		if (user == null) {
			throw new UsernameNotFoundException("Invalid username/password.");
		}

		List<Group> groups = identityService.createGroupQuery().groupMember(username).list();

		List<SimpleGrantedAuthority> authorities = new ArrayList<SimpleGrantedAuthority>();
		for (Group group : groups) {
			String id = group.getId();
			authorities.add(new SimpleGrantedAuthority(id));
		}

		return new User(user.getId(), user.getPassword(), authorities);
	}

}
